<template>
  <div>
    <div :id="id"></div>
  </div>
</template>

<script>
import Highcharts from 'highcharts'
import Exporting from 'highcharts/modules/exporting'
import Wordcloud from 'highcharts/modules/wordcloud'
Exporting(Highcharts)
Wordcloud(Highcharts)
export default {
  data() {
    return {
      id: 'charts',
      option: {
        series: [{
          type: 'wordcloud',
          data: [],
          name: ''
        }],
        title: {
          text: '词云图'
        },
        credits: {
          enabled: false
        },
        tooltip: {
          shared: true,
          useHTML: true,
          headerFormat: `<big>{point.key}</big><table>`,
          pointFormat: `<tr><td style="color: {series.color}">{series.name}: </td>
          <td style="text-align: right"><b>{point.weight}</b></td></tr>`,
          footerFormat: `</table>`,
          valueDecimals: null
        }
      }
    }
  },
  props: {
    keywords: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: '词云图'
    },
    weight: {
      type: String,
      default: '权重'
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      const data = this.keywords.split(/[,\. ]+/g).reduce((arr, word) => {
        var obj = arr.find(obj => {
          return obj.name === word
        })
        word = word.split('|')
        if (obj) {
          obj.weight += 1
        } else {
          obj = {
            name: word[0],
            weight: Number(word[1]) || 1
          }
          arr.push(obj)
        }
        return arr
      }, [])
      this.option.series[0].data = data
      this.option.series[0].name = this.weight
      this.option.title = this.title
      Highcharts.chart(this.id, this.option)
    }
  },
  watch: {
    keywords(newValue, oldValue) {
      this.initData()
    }
  }
}
</script>

<style scoped>
</style>
